/*
 * @Description  : 系统服务
 * @Date         : 2021-06-02 14:22:41
 * @Author       : 保锋
 * @LastEditTime : 2021-06-02 15:20:19
 * @LastEditors  : 保锋
 * @FilePath     : \caiying_flutter\lib\services\system_sercvices.dart
 */
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:yinshui_caiying/http/apis.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/version_result_model.dart';
import 'package:ota_update/ota_update.dart';

///系统服务类
class SystemService extends GetxService {
  @override
  void onInit() {
    _checkVersion();
    super.onInit();
  }

  Future<SystemService> init() async {
    return this;
  }

  ///版本号
  RxString _vInfo = ''.obs;

  ///进度条
  String _progress = '';

  final _serviceVersion =
      VersionModel(androidMsg: [], androidUrl: '', androidVersion: '').obs;

  late OtaEvent currentEvent;

  ///初始化数据
  // void _initData() async {
  //   PackageInfo packageInfo = await PackageInfo.fromPlatform();
  //   String version = packageInfo.version;
  //   _vInfo.value = Platform.isIOS ? 'iOS_$version' : 'android_$version';
  // }

  ///检测当前app版本
  _getCurrentVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var currentVersion = packageInfo.version;
    return currentVersion;
  }

  ///版本校验
  _checkVersion() async {
    await _getServiceVersion();
    var currentVersion = await _getCurrentVersion();
    print(currentVersion);
    if (currentVersion == _serviceVersion.value.androidVersion) {
      //验证通过，什么也不做

    } else {
      //版本不符弹出对话框
      _showUpdateDialog();
    }
  }

  ///获取服务器版本信息
  _getServiceVersion() async {
    try {
      var res = await Http().post(
        ApiSystem.COLLECT_VERSION,
      );
      VersionResultModel result = VersionResultModel.fromJson(res);

      if (result.code == 200) {
        _serviceVersion(result.content.data);
      } else {}
    } catch (e) {}
  }

  ///弹窗内容
  Widget upDateDialog() {
    List<Widget> contentList = [];
    var style = TextStyle(
      fontSize: 15,
    );
    contentList.addAll(_serviceVersion.value.androidMsg.map((item) {
      return Text(
        item,
        style: style,
      );
    }).toList());
    contentList.insert(
        0,
        Container(
          height: 0.4,
          color: Colors.black,
          margin: EdgeInsets.only(top: 5, bottom: 5),
        ));
    return CupertinoAlertDialog(
      title: Text('版本更新',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
      content: Container(
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: contentList),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text('取消'),
          textColor: Colors.grey,
          onPressed: () {
            Get.back();
            // _goNextPage();
          },
        ),
        FlatButton(
          child: Text('更新'),
          textColor: Colors.blue,
          onPressed: () async {
            if (Platform.isAndroid) {
              //安卓应用内下载
              Get.back();
              tryOtaUpdate();
            } else {
              //ios 跳转商店
              // if(await canLaunch(serviceVersion.iosAddress)){
              //   await launch(serviceVersion.iosAddress);
              // }else{
              //   throw 'Could not launch ';
              // }
            }
          },
        )
      ],
    );
  }

  ///打开弹窗内容
  _showUpdateDialog() {
    Get.dialog(
      upDateDialog(),
      barrierDismissible: false,
    );
  }

  ///andriod升级
  Future<void> tryOtaUpdate() async {
    try {
      OtaUpdate()
          .execute(_serviceVersion.value.androidUrl,
              destinationFilename: 'collect.apk')
          .listen(
        (OtaEvent event) {
          // setState(() => currentEvent = event);
        },
      );
    } catch (e) {
      print('Failed to make OTA update. Details: $e');
    }
  }
}
